package com.wyp.didishige.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wyp.didishige.utils.DateUtil;
import com.wyp.didishige.R;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.ImageLoadOptions;
import com.wyp.didishige.utils.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobGeoPoint;

/**
 * 附近的人
 *
 * @author smile
 * @ClassName: BlackListAdapter
 * @Description: TODO
 * @date 2014-6-24 下午5:27:14
 */
public class NearPeopleAdapter extends BaseListAdapter<User> {

    public NearPeopleAdapter(Context context, List<User> list) {
        super(context, list);
    }

    @Override
    public View bindView(int arg0, View convertView, ViewGroup arg2) {
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item_near_people, null);
        }
        final User contract = getList().get(arg0);
        TextView tv_name = ViewHolder.get(convertView, R.id.tv_name);
        TextView tv_distance = ViewHolder.get(convertView, R.id.tv_distance);
        TextView tv_logintime = ViewHolder.get(convertView, R.id.tv_logintime);
        ImageView iv_avatar = ViewHolder.get(convertView, R.id.iv_avatar);
        TextView user_gender = ViewHolder.get(convertView, R.id.user_gender);
        ImageView vip_lv = ViewHolder.get(convertView, R.id.vip_lv);
        TextView publish_community = ViewHolder.get(convertView, R.id.publish_community);

        String avatar = contract.getAvatar();
        if (avatar != null && !avatar.equals("")) {
            ImageLoader.getInstance().displayImage(avatar, iv_avatar,
                    ImageLoadOptions.getOptions());
        } else {
            iv_avatar.setImageResource(R.drawable.ic_launcher);
        }
        String age = DateUtil.getAge(contract.getUserBirthday()) + "";
        user_gender.setText(age);

        if (contract.getSex() != null && contract.getSex()) {
            user_gender.setBackgroundResource(R.drawable.user_male_bg);
            user_gender.setCompoundDrawablesWithIntrinsicBounds(mContext.getResources().getDrawable(R.drawable.ic_user_male), null, null, null);
        } else {
            user_gender.setBackgroundResource(R.drawable.user_female_bg);
            user_gender.setCompoundDrawablesWithIntrinsicBounds(mContext.getResources().getDrawable(R.drawable.ic_user_famale), null, null, null);
        }

        int level = contract.getLevel();
        if (level >= 1 && level < 3) {
            vip_lv.setImageResource(R.drawable.vip_lv_1);
            vip_lv.setVisibility(View.VISIBLE);
        } else if (level >= 3 && level < 6) {
            vip_lv.setImageResource(R.drawable.vip_lv_3);
            vip_lv.setVisibility(View.VISIBLE);

        } else if (level >= 6 && level < 12) {
            vip_lv.setImageResource(R.drawable.vip_lv_6);
            vip_lv.setVisibility(View.VISIBLE);

        } else if (level >= 9) {
            vip_lv.setImageResource(R.drawable.vip_lv_12);
            vip_lv.setVisibility(View.VISIBLE);

        } else {
            vip_lv.setVisibility(View.GONE);
        }

        BmobGeoPoint location = contract.getLocation();
        User user = BmobUser.getCurrentUser(mContext, User.class);
        if (user.getLocation()!=null){
            String currentLat = user.getLocation().getLatitude() + "";
            String currentLong = user.getLocation().getLongitude() + "";
            if (location != null && !currentLat.equals("") && !currentLong.equals("")) {
                int distance = (int)DistanceOfTwoPoints(Double.parseDouble(currentLat), Double.parseDouble(currentLong), contract.getLocation().getLatitude(),
                        contract.getLocation().getLongitude());
                distance = distance / 1000;
                tv_distance.setText(String.format("%s千米", distance));
            } else {
                tv_distance.setText("未知");
            }
        }else{
            tv_distance.setText("未知");
        }

        if (!StringUtils.isNullOrEmpty(contract.getCommunity())){
            publish_community.setText(contract.getCommunity());
            publish_community.setVisibility(View.VISIBLE);
        }else{
            publish_community.setVisibility(View.GONE);
        }
        tv_name.setText(contract.getNick());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        2015-04-22 23:54:13
        Date date = new Date();
        try {
            date = simpleDateFormat.parse(contract.getUpdatedAt());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);

        tv_logintime.setText(String.format("%s", DateUtil.getDateSpan(calendar.getTimeInMillis() / 1000,
                DateUtil.getTimestamp(new Date()))));
        return convertView;
    }

    private static final double EARTH_RADIUS = 6378137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 根据两点间经纬度坐标（double值），计算两点间距离，
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return 距离：单位为米
     */
    public static double DistanceOfTwoPoints(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

}
